package com.woniu.map.remote;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.woniu.internalcommon.request.POIRequestDTO;
import com.woniu.internalcommon.response.POIResponse;
import com.woniu.map.remote.url.POISearchUrl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
@Slf4j
public class POISearchClient {

    @Autowired
    private POISearchUrl poiSearchUrl;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 向谷歌发出地图周边搜索请求
     * @param poiRequestDTO
     * @return
     */

    public List<POIResponse> aroundPOISearch(POIRequestDTO poiRequestDTO) {
        //将数组拆分 用|拼接
        System.out.println(poiRequestDTO.getTypes());
        String typesStr = String.join("|", poiRequestDTO.getTypes());
        String url = poiSearchUrl.buildAroundPOISearchUrl
                (poiRequestDTO.getLocation(), poiRequestDTO.getRadius(), typesStr);

        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);

        log.info("高德地图周边POI搜索结果："+forEntity.getBody());
        return parseAroundPOIResponse(forEntity.getBody());


    }
    private  List<POIResponse> parseAroundPOIResponse(String body) {
        if (StringUtils.isEmpty(body))
            throw new IllegalArgumentException("请求失败");
        JSONObject response = JSONObject.parseObject(body);
        if (!response.get("infocode").equals("10000")) {
            throw new IllegalArgumentException("周边搜索请求响应失败");
        }
        log.info("周边搜索响应结果：{}",response);
        return response.getJSONArray("pois").toJavaList(POIResponse.class);

    }
}
